<?php
/**
 * @author spenceryg
 * @date 2022/11/27
 * @time 12:55 下午
 * @focus love & life
 */


namespace app\auto\business;


use app\admin\controller\auto\service\AutoService;
use app\auto\model\Field;
use app\auto\model\Table;
use app\auto\validate\FieldValidate;
use app\common\lib\mysql\TableModify;
use app\common\lib\mysql\TableParse;
use app\common\lib\mysql\TpTableModify;
use think\exception\ValidateException;
use function GuzzleHttp\Psr7\str;

class FieldBusiness
{
    public static $model = "app\\auto\\model\\Field";

    use \app\common\traits\business\BusinessTrait;


    /**
     * 创建表字段
     * createField
     * @param $table_name
     * @param $model
     * @throws \Exception
     */
    public static function createField($table_name, $model)
    {
        $mysqlGenerator = new TpTableModify($table_name);
        $mysqlGenerator
            ->add(
                $model->getAttr('name'),
                $model->getAttr('type'),
                $model->getAttr('default')===''?null:$model->getAttr('default'),
                $model->getAttr('length'),
                $model->getAttr('comment'),
                $model->getAttr('is_null')
            )->execute();
    }


    /**
     * add
     * @param $data
     * @return Field|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function add($data)
    {
        validate(FieldValidate::class)->check($data);
        $table_name = Table::find($data['table_id'])['name'];
        $table_fields = (new TableParse($table_name))->getColumns();
        if(in_array($data['name'], array_column($table_fields, 'name'))) {
            throw new ValidateException("数据表字段{$data['name']}已经存在！");
        }
        if(!$data['is_sys']) {
            $data['sort'] = (count($table_fields) + 1) * 10;
        }
        $config = self::getFieldDefaultConfig($data);
        $data['config'] = $config;

        $field = Field::create($data);
        self::createField($table_name,$field);
        return $field;
    }


    public static function getFieldDefaultConfig($data): array
    {
        $table = Table::find($data['table_id']);
        $config = [];
        $config['comment'] = $table['comment'] . $data['comment'];
        $config['inline'] = 0;
        $config['width'] = '';
        $config['height'] = '';
        $config['date'] = 0;
        $config['time'] = 0;
        $type = $data['type'];
        switch ($type) {
            case 'varchar':
                $config['type'] = 'input';
                $map_keywords = ['地图','位置'];
                foreach ($map_keywords as $keyword) {
                    if (strpos($data['comment'], $keyword) !== false) {
                        $config['type'] = 'baidumap';
                        break;
                    }
                }
                $img_keywords = ['图片', '照片', '封面', '头像'];
                foreach ($img_keywords as $keyword) {
                    if (strpos($data['comment'], $keyword) !== false) {
                        $config['type'] = 'image';
                        break;
                    }
                }
                $file_keywords = ['文件','文档'];
                foreach ($file_keywords as $keyword) {
                    if (strpos($data['comment'], $keyword) !== false) {
                        $config['type'] = 'file';
                        break;
                    }
                }
                $video_keywords = ['视频', '音乐', '歌曲'];
                foreach ($video_keywords as $keyword) {
                    if (strpos($data['comment'], $keyword) !== false) {
                        $config['type'] = 'video';
                        break;
                    }
                }
                break;
            case 'text':
                $config['type'] = 'textarea';
                $img_keywords = ['图片', '照片', '封面', '头像', '图册', '相册', '图集', '多图'];
                foreach ($img_keywords as $keyword) {
                    if (strpos($data['comment'], $keyword) !== false) {
                        $config['type'] = 'morepic';
                        break;
                    }
                }
                break;
            case 'longtext':
                $config['type'] = 'editor';
                break;
            case 'tinyint':
                if(strpos($data['comment'], '是否') !== false) {
                    $config['type'] = 'radio';
                    $config['data_set'] = "1__是\r\n0__否";

                }
                break;
            case 'int':
                // 各种其他表的id
                if(strpos($data['name'], '_id') !== false) {
                    $config['type'] = 'select';
                }
                else if(strpos($data['comment'], '日期') !== false) {
                    $config['type'] = 'date';
                }
                else if(strpos($data['comment'], '时间') !== false) {
                    $config['type'] = 'time';
                } else {
                    $config['type'] = 'input';
                }
                break;
            default:
                $config['type'] = 'input';
                break;
        }
        return $config;
    }


    public static function update($data)
    {
        validate(FieldValidate::class)->check($data);
        $table_name = Table::find($data['table_id'])['name'];
        $origin_data = Field::find($data['id']);
        $mysqlGenerator = new TpTableModify($table_name);
        $mysqlGenerator
            ->modify($origin_data['name'], $data['name'], $data['type'],$data['default']==''?null:$data['default'], $data['length'], $data['comment'], $data['is_null'])
            ->execute();
        $field = Field::update($data);
        return $field;
    }


    public static function delete($id)
    {
        $field = Field::find($id);
        $table_name = Table::find($field['table_id'])['name'];
        $field_name = $field['name'];
        $table_fields = (new TableParse($table_name))->getColumns();
        if(in_array($field_name, array_column($table_fields, 'name'))) {
            (new TpTableModify($table_name))->delete($field_name)->execute();
        }
        Field::destroy($id);

    }


    /**
     * 根据field的主键id获取别名
     * getFiledAliasById
     * @param $id
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getFiledAliasById($id): string
    {
        $field = Field::find($id);
        $table = Table::find($field['table_id']);
        return str_replace(env('DATABASE.PREFIX'), '', $table['name'])  . '__' . $field['name'];
    }
}
